﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using WindowsTaskDialog;

namespace AppExceptions
{

    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class HandleExceptionDialog : IExceptionHandler
    {
        public static string LogFileName { get; set; }
        public static string ContextFilePath { get; set; }

        private string GetLogFileName()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + LogFileName;
        }

        readonly TaskDialog _taskDialog = new TaskDialog { };

        public HandleExceptionDialog(NameValueCollection attributes) { }
        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            Contract.Requires(exception != null);
            Contract.Ensures(Contract.Result<Exception>() != null);
            _taskDialog.Content = GetMessage(exception);
            _taskDialog.MainIcon = TaskDialogIcon.Error;
            _taskDialog.MainInstruction = "Зарегистрирована ошибка";
            _taskDialog.WindowTitle = "Ошибка";
            _taskDialog.EnableHyperlinks = true;
            _taskDialog.Footer = string.Format("<A HREF=\"file:///{0}\"> Показать журнал </A>  <A HREF=\"file:///{1}\">Показать данные контекста </A>", GetLogFileName(), ContextFilePath);
            _taskDialog.Callback += new TaskDialogCallbackEventHandler(dlg_Callback);

            try
            {
                _taskDialog.Show(null);
            }
            catch (Exception e)
            {
                Logger.Write("Ошибка создания TaskDialog:" + e.Message);
                MessageBox.Show(GetMessage(exception), "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return exception;
        }

        private static string GetMessage(Exception exception)
        {
            var stringBuilder = new StringBuilder();
            var ex = exception;
            while (ex != null)
            {
                stringBuilder.Append(ex.Message);
                stringBuilder.Append("\n");
                ex = ex.InnerException;
            }
            return stringBuilder.ToString();
        }

        void dlg_Callback(object sender, TaskDialogCallbackEventArgs e)
        {
            if (e.Notification == TaskDialogNotification.HyperlinkClicked)
            {
                //
                // Open link.
                //
                System.Diagnostics.Process.Start(e.Hyperlink);
            }
        }
    }
}
